package com.example.factory;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName MybatisFactoryCnnfig
 * @Description
 * @Author Yin
 * @Date 2021/4/8 15:37
 * @Version 1.0
 */
public class MybatisFactoryConfig implements FactoryBean {

    private Class mapperClass; // 表示一个mapper接口
    private SqlSession sqlSession;

    public MybatisFactoryConfig(Class mapperClass) {
        this.mapperClass = mapperClass;
    }

    @Autowired
    public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(mapperClass);
        this.sqlSession = sqlSessionFactory.openSession();
    }

    @Override
    public Object getObject() throws Exception {
        // UserMapper的代理对象 ， 想办法获取mybatis生成的代理对象
        return sqlSession.getMapper(mapperClass);
    }

    @Override
    public Class<?> getObjectType() {
        return mapperClass;
    }
}
